package rtm;

import java.io.IOException;
import java.util.List;

import org.xml.sax.SAXException;

import rtm.authentication.FrobHandler;
import rtm.authentication.TokenHandler;
import rtm.core.CommandFacade;
import rtm.core.RtmCallException;
import rtm.core.UrlBuilder;
import rtm.task.Task;
import rtm.task.TaskListHandler;

import com.google.inject.Inject;

public class SessionImpl implements Session {

	@Inject private CommandFacade command;
	@Inject private UrlBuilder urlBuilder;
	
	
	private String frob;
	private String token;
	
	@Override
	public void setFrob(String frob) {

		this.frob = frob;
	}
	
	@Override
	public void setToken(String token) {
		this.token = token;
	}
	
	@Override
	public String getAuthenticationUrl() throws RtmCallException, IOException, SAXException {
		
		final FrobHandler handler = new FrobHandler();
		command.call(urlBuilder.getSigned("rtm.auth.getFrob"), handler);
		this.frob = handler.getFrob();
		
		return urlBuilder.getLoginURL(frob);
	}
	
	@Override
	public void verifyPermission() throws IOException, RtmCallException, SAXException {
		
		final TokenHandler handler = new TokenHandler();
		command.call(urlBuilder.getSigned("rtm.auth.getToken", frob), handler);
		this.token = handler.getToken();
		
		System.out.println("token:" + token);
	}
	
	
	@Override
	public List<Task> getAllTasks() throws IOException, RtmCallException, SAXException {
		
		final TaskListHandler handler = new TaskListHandler();
		
		command.call(urlBuilder.getAuthenticated("rtm.tasks.getList", token),  handler);
				
		return handler.getTasks();
	}
}
